package cn.lsoft.undoner.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.lsoft.undoner.model.User;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.lsoft.undoner.util.Contants;

public class LoginInterceptor implements HandlerInterceptor {
	@SuppressWarnings("unused")
	private static final Logger LOGGER = Logger.getLogger(LoginInterceptor.class);
	
	private boolean isNeedReLogin(HttpSession session, HttpServletRequest request) {
        Object user = session.getAttribute(Contants.LOGIN);
        if (user != null && request.getUserPrincipal() != null && request.getUserPrincipal().getName() != null
                && !request.getUserPrincipal().getName().equalsIgnoreCase(((User) user).getUserName())) {
            return true;
        }
        return false;
    }

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
        User user = (User) session.getAttribute(Contants.LOGIN);
        if (request.getRequestURL().indexOf("/user/login") > 0) {
        	return true;
        }

        if (user == null || isNeedReLogin(session, request)) {
        	response.sendRedirect(request.getContextPath() + "/user/login");
        	return false;
        }
        return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		
	}
}
